<template>
  <div class="card content-box">
    <span class="text">隐私协议</span>
    <WangEditor v-model:value="content" height="500px" />

    <div class="button-group">
      <el-button type="primary" @click="handlePreview">内容预览</el-button>
      <el-button type="success" @click="handleSave">保存内容</el-button>
    </div>

    <!-- 预览弹窗 -->
    <el-dialog v-model="dialogVisible" title="隐私协议内容预览" width="1300px" top="50px">
      <div class="view" v-html="content"></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="wangEditor">
import { ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";
import { getAgreementContent, saveAgreementContent } from "@/api/modules/agreement";

const content = ref("");
const originalContent = ref(""); // 保存原始内容用于比较
const dialogVisible = ref(false);
const hasUnsavedChanges = ref(false);

// 初始化时获取原始内容
const fetchOriginalContent = async () => {
  // 这里应该是从API获取原始内容的逻辑
  // 模拟API调用
  try {
    const res = await getAgreementContent();
    originalContent.value = res.data.privacyContent;
    content.value = res.data.privacyContent || "请输入隐私协议";
  } catch (error) {
    ElMessage.error("获取隐私协议内容失败");
  }
};

// 初始化
fetchOriginalContent();

// 监听内容变化
watch(
  content,
  newVal => {
    hasUnsavedChanges.value = newVal !== originalContent.value;
  },
  { deep: true }
);

// 预览处理
const handlePreview = () => {
  if (!content.value) {
    ElMessage.warning("请输入内容后再预览");
    return;
  }
  dialogVisible.value = true;
};

// 保存处理
const handleSave = () => {
  if (!content.value) {
    ElMessage.warning("请输入内容后再保存");
    return;
  }

  if (!hasUnsavedChanges.value) {
    ElMessage.info("内容未修改，无需保存");
    return;
  }
  ElMessageBox.confirm("是否保存？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await saveAgreementContent({ privacyContent: content.value });
      if (res.code == "200") {
        ElMessage.success("保存成功");
        originalContent.value = content.value;
      } else {
        ElMessage.error("保存失败");
      }
    })
    .catch(() => {
      // 取消操作
      ElMessage.info("已取消");
    });
};
</script>

<style scoped lang="scss">
@import "./index.scss";
.content-box {
  padding: 20px;
}
.text {
  display: block;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}
.button-group {
  margin-top: 20px;
  .el-button {
    margin-right: 15px;
  }
}
.view {
  min-height: 300px;
  padding: 10px;
  border: 1px solid #eeeeee;
  border-radius: 4px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
